<?php

class DatabaseObject_HelpCategories extends DatabaseObject {

    public $_parent = null;
    public $childs = null;
    public $pages = null;

    public function __construct($db) {
        parent::__construct($db, 'help_cats', 'id');

        $this->add('alias');
        $this->add('name');
        $this->add('parent_id');
        $this->add('image');
        $this->add('descr');
    }

    public function postLoad() {
        parent::postLoad();

        $this->loadParent();
        if($this->parent_id != 0)
            $this->pages = DatabaseObject_HelpPages::GetPages ($this->getDb(), $this->getId());

        return true;
    }
    
    public function preDelete() {
        parent::preDelete();
        
        $cats = DatabaseObject_HelpCategories::GetCategories($this->getDb(), $this->getId());
        foreach ($cats as $cat) {
            $cat->delete();
        }
        
        return true;
    }

    public function getParent() {
        return $this->_parent;
    }
    
    public function loadParent() {
        if ($this->parent_id != 0) {
            $this->_parent = new DatabaseObject_HelpCategories($this->getDb());
            $this->_parent->load($this->parent_id);
        }
    }

    public static function GetCategories($db, $parentId = 0, $options = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'p.*');

        $select->where('parent_id = ?', $parentId);
        

        // получим данные из базы
        $data = $db->fetchAll($select);

        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);

        if (count($cat_ids) == 0)
            return array();

        if ($parentId != 0) {
            foreach ($cats as $cat) {
                $cat->loadParent();
                $cat->pages = DatabaseObject_HelpPages::GetPages ($db, $cat->getId());
            }
        }

        return $cats;
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('p' => 'help_cats'), array());

        return $select;
    }
}
